package com.heima.home.service.impl;

import com.heima.home.entity.Users;
import com.heima.home.mapper.BookingMapper;
import com.heima.home.mapper.FavoritesMapper;
import com.heima.home.mapper.ReviewsMapper;
import com.heima.home.util.JwtUtil;
import com.heima.home.dto.LoginRequest;
import com.heima.home.dto.RegisterRequest;
import com.heima.home.dto.UserInfoResponse;
import com.heima.home.exception.CustomException;
import com.heima.home.mapper.UserMapper;
import com.heima.home.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private BookingMapper bookingMapper;
    
    @Autowired
    private ReviewsMapper reviewsMapper;
    
    @Autowired
    private FavoritesMapper favoritesMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public void register(RegisterRequest request) {
        // 1. 检查用户名是否已存在
        if (userMapper.findByUsername(request.getUsername()) != null) {
            throw new CustomException("用户名已存在");
        }
        // 2. 检查邮箱是否已存在
        if (userMapper.findByEmail(request.getEmail()) != null) {
            throw new CustomException("邮箱已被注册");
        }

        // 3. 创建用户实体并加密密码
        Users user = new Users();
        user.setUsername(request.getUsername());
        user.setEmail(request.getEmail());
        user.setPassword(passwordEncoder.encode(request.getPassword()));

        // 4. 插入数据库
        userMapper.insert(user);
    }

    @Override
    public String login(LoginRequest request) {
        // 1. 根据用户名查找用户
        Users user = userMapper.findByUsername(request.getUsername());
        if (user == null) {
            throw new CustomException("用户名或密码错误");
        }

        // 2. 检查用户状态是否正常
        if (user.getStatus() != 1) {
            throw new CustomException("该账户已被禁用");
        }

        // 3. 验证密码
        if (!passwordEncoder.matches(request.getPassword(), user.getPassword())) {
            throw new CustomException("用户名或密码错误");
        }

        // 4. 生成JWT
        System.out.println("从数据库查出的用户信息: " + user.toString());
        return jwtUtil.createToken(user);
    }

    @Override
    public UserInfoResponse getUserInfo(Integer userId) {
        Users user = userMapper.findById(userId);
        if (user == null) {
            throw new CustomException("用户不存在");
        }
        // 使用DTO转换，避免泄露密码等敏感信息
        UserInfoResponse response = UserInfoResponse.fromUser(user);
        
        // 获取统计数据
        Integer totalOrders = bookingMapper.countByUserId(userId);
        Integer totalReviews = reviewsMapper.countByUserId(userId);
        Integer totalFavorites = favoritesMapper.countByUserId(userId);
        
        response.setTotalOrders(totalOrders != null ? totalOrders : 0);
        response.setTotalReviews(totalReviews != null ? totalReviews : 0);
        response.setTotalFavorites(totalFavorites != null ? totalFavorites : 0);
        
        return response;
    }

    @Override
    public void updateAvatar(Integer userId, String avatar) {
        int updated = userMapper.updateAvatar(userId, avatar);
        if (updated == 0) {
            throw new CustomException("更新头像失败");
        }
    }

    @Override
    public int updateUserInfo(Users user) {
        // 如果密码不为空，需要加密
        if (user.getPassword() != null && !user.getPassword().isEmpty()) {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        }
        else {
            user.setPassword(userMapper.findById(user.getId()).getPassword());
        }
        return userMapper.updateUserInfo(user);
    }
}